package com.fsbm.ctech.maxis.ebpsbackend;

import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.persist.*;
import com.checkfree.isolutions.statement.*;
import com.checkfree.isolutions.statement.persist.*;
import com.checkfree.isolutions.utility.*;
import com.checkfree.isolutions.admin.*;
import com.checkfree.isolutions.streaming.*;
import com.checkfree.isolutions.admin.ObjectId;

import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Vector;
import java.util.Properties;


import java.io.*;
import java.text.*;
import java.util.*;
import java.util.Date;
import java.sql.*;

/*
 * Batch Program to update the emaildelivery log table after the log file with job no
 * is created by unix ftp shell script
 * @author Meau
 */

public class UpdateFtpLog {
    static ConfigObject cfgObj = new ConfigObject();

    public static void main(String argv[]) {
		String strFile="";
        for (int optind = 0; optind < argv.length; optind++) {
            if (argv[optind].toLowerCase().indexOf("-file") != -1) {
                strFile = argv[optind];
                strFile = strFile.substring(strFile.indexOf("=")+1);
            } else if (argv[optind].toLowerCase().startsWith("-h")) {
                printUsage();
                System.exit(1);
            } else {
                break;
            }
        }

        if(!strFile.equals("")){
			updateFtpLogfile(strFile);
		}else{
			printUsage();
			System.exit(1);
		}
    }

	private static void updateFtpLogfile(String fileName){

		try {
			// Stream used to read the log file
			FileInputStream fstream = new FileInputStream(fileName);
			DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));

	        // Information to be uploaded to the emaildelivery table
		    String strLine;
            String jobNo = "";
            String fileToPutName = "";
            String ftpResponse = "";

            //To check if want to update to emaildelivery log table
            boolean boolJobExist=false;
            boolean boolLocalExist=false;

            // To skip the first PORT command
            boolean boolFirstPortCmd = true;

            // To make sure there no data missing for line job and line local
            String testJob="";
            String testLocal="";

		    //Read File Line By Line
		    while ((strLine = br.readLine()) != null)   {

				if(strLine.indexOf("226 JOB")>-1){
					if(strLine.indexOf("complete")>-1){
						testJob = strLine;
						ftpResponse = strLine;
                		StringTokenizer st = new StringTokenizer((String)strLine," ");

                		// loop 3 times, since job no is the fourth token
                		for(int i =0;i<3;i++){
							st.nextToken();
						}
						jobNo = st.nextToken();

        		        boolJobExist = true;
						//System.out.println (strLine);
					}
				}
				if(strLine.indexOf("local")>-1){
					testLocal = strLine;
					StringTokenizer st = new StringTokenizer((String)strLine,":");
                	// loop 2 times, since job no is the third token
                	for(int i =0;i<2;i++){
						st.nextToken();
					}
					fileToPutName = st.nextToken().trim();


		           boolLocalExist = true;
					//System.out.println (strLine);
				}

				if(boolJobExist && boolLocalExist){
					System.out.println ("Updating email delivery log with(jobno,filename,ftpresponse).... ("+jobNo+","+fileToPutName+","+ftpResponse+")");
					DBLog.updateDeliveryRecord(jobNo,fileToPutName,ftpResponse);
					boolLocalExist=false;
					boolJobExist=false;
				}

				// Not the first PORT command, check if any of the test line is ""
				if(!boolFirstPortCmd && strLine.indexOf("200 PORT")>-1){
					// Check the previous line 1(job no) and line 2(local)
					if(testJob.equals("") || testLocal.equals("")){
						//Write to error file since 1 line of expected data is missing
						cfgObj.write("Error occur for " + fileName,"ErrAdhoc");
						cfgObj.write("The 200 JOB line is " + testJob,"ErrAdhoc");
						cfgObj.write("The local line is " + testLocal,"ErrAdhoc");
					}

				}

				if(strLine.indexOf("200 PORT")>-1){
					boolFirstPortCmd=false;
				}



		      // Print the content on the console
		      //System.out.println (strLine);
		    }
		    //Close the input stream
		    in.close();
		    fstream.close();
		    br.close();
		}catch (ArrayIndexOutOfBoundsException e){
			printUsage();
		}catch (IOException e){
			// If another exception is generated, print a stack trace
			e.printStackTrace();
		}catch (Exception e) {
			System.err.println("Error updating ftp log file file " + fileName);
            System.err.println(e.getMessage());
            e.printStackTrace();
        }

	}

    public static void printUsage() {
          System.out.println("\nCopyright (c) 2009 MYeBills Consulting Sdn Bhd (739522-W).");
          System.out.println("All rights reserved.");
          System.out.println("\n\nUsage : UpdateFtpLog.sh [-file=FILENAME]");
          System.out.println("or :");
          System.out.println("\tjava -server -Xms[HS] -Xmx[HS] -DBGROOT=/app/cfi/v55 UpdateFtpLog");
          System.out.println("\t[-file=FILENAME]");
          System.out.println("\n\nWhere:");
          System.out.println("\t -[FILENAME] where log file name generated by the ftp job during transfer");
          System.out.println("\t -[HS] Min and Max Heap Memory size allocation");
          System.out.println("\n\tor java Deliver -h for help options");
          System.out.println("\tor UpdateFtpLog.sh -h for help options");
     }

} //end of class UpdateFtpLog